#pragma once

#define TASKNUMS 3
typedef void (*task_t)(); // task_t 函数指针类型

void Print()
{
    std::cout << "I am print task" << std::endl;
}
void DownLoad()
{
    std::cout << "I am a download task" << std::endl;
}
void Flush()
{
    std::cout << "I am a flush task" << std::endl;
}

task_t tasks[TASKNUMS];

void LoadTask()
{
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

void ExcuteTask(const int& taskid)
{
    std::cout << "excute task : " << taskid << std::endl;
    tasks[taskid]();
}

void work()
{
    while(true)
    {
        int taskid = 0;
        int n = read(0, &taskid, sizeof(taskid));
        if (n == sizeof(taskid))
        {
            std::cout << "pid is : " << getpid() << " hander task" << std::endl;
            ExcuteTask(taskid);
        }
        else
        {
            std::cout << "pid is : " << getpid() << " quit" << std::endl;
            break;
        }
    }
}

void SandTaskid(channel& ch, int& taskid)
{
    write(ch.GetWfd(), &taskid, sizeof(taskid));
    std::cout << "pid is : " << getpid() << " sand task " << taskid << " to "<< ch.GetChannelName() << std::endl;
}

int SelectChannel(int channelNum)
{
    static int num = 0;
    num++;
    num %= channelNum;
    return num;
}

int SelectTask()
{
    return rand() % TASKNUMS;
}

void CtrlProcess(std::vector<channel>& channels)
{
    int taskid = SelectTask();
    int channelid = SelectChannel(channels.size());
    SandTaskid(channels[channelid], taskid);
}

void TaskInit()
{
    LoadTask();
    srand(time(0));
}